package com.yuzhihao.writejvm.constant;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * The CONSTANT_String_info Structure
 *
 * @author yzh
 * @since 2021年12月01日19:03:33
 */

@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class ConstantStringInfo extends ConstantPool {

    private int string_index_u2 = 2;

    private int string_index;

    private String constant;

    public ConstantStringInfo(Map<String, ConstantPool> pools) {
        super(pools);
        super.name = "String";
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        try {
            this.string_index = Parse.byteToInt(string_index_u2, dis);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public String getConstant() {
        if (Objects.nonNull(this.constant)) {
            return this.constant;
        }

        ConstantPool cp = pools.get(String.valueOf(this.string_index));
        if (cp instanceof ConstantUtf8Info) {
            ConstantUtf8Info utf = (ConstantUtf8Info) cp;
            this.constant = utf.getConstant();
        }

        return constant;
    }

    @Override
    public String print() {
        StringBuilder builder = new StringBuilder();
        builder.append(PrintFormat.MEMPTY)
                .append(PrintFormat.HASHTAG)
                .append(this.string_index)
                .append(PrintFormat.MEMPTY)
                .append(PrintFormat.DOUBLE_SLASH).append(PrintFormat.EMPTY)
                .append(this.getConstant());

        return builder.toString();
    }

}
